/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {Button, Card, Form, Icon, Modal, notification, Table, Tabs, Tag, Upload} from 'antd';

import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import DescGroup from "../../../components/DescriptionGroup";
import ViewTitle from "../../../components/ViewTitle";
import _ from "lodash";
import {FormField, FormLayout, ModalView} from "antd-extra";
import styles from "../../index.less";
import TextArea from "antd/es/input/TextArea";
import notify from "../../../components/NotificationExtra";
import ModalTaskDetail from "./ModalTaskDetail";
import ModalCreateOrEditWork from "./ModalCreateOrEditWork";

const {TabPane} = Tabs;
moment.locale('zh-cn');
const table = 'Work';
@Form.create()
@connect(({user, global, work}) => ({...user, ...work, ...global}))
export default class ModalWorkDetail extends FormBase {
  constructor(props) {
    super(props);
    // const {record} = props;
    // this.state = {...record};
  }

  componentDidMount() {
    const {record} = this.props;
    const {code} = record;
    this.props.dispatch({
      type: 'global/getModel',
      payload: {table}
    });

    this.props.dispatch({
      type: 'work/findWork',
      payload: {code}
    });
    const login = this.getLoginInfo();
    if (login.isAdmin) {
      this.props.dispatch({
        type: 'work/findWorkMany',
        payload: {adminCode: code, isAdmin: true}
      });
    }
    // this.props. dispatch({
    //   type: 'work/findWorkMany',
    //   payload: {workCode: code}
    // });
  }

  columns = (isChild) => {
    const model = this.props[`${table}Model`];
    if (!model) return [];
    const temp = [];
    temp.push(
      {title: '任务编码', dataIndex: 'code', key: 'code'},
      // {title: '创建人', dataIndex: 'createUsername', key: 'createUsername'},
      // {title: '责任人', dataIndex: 'username', key: 'username'},
      {
        title: '责任人关系', dataIndex: 'username', key: 'username', render: (text, record) => {
          const {createUsername, username} = record;
          return <div>{`【${createUsername}】 分配给 【${username}】`}</div>;
        }
      },
      {title: '事项', dataIndex: 'desc', key: 'desc', ellipsis: true},
      {
        title: '要求完成时间',
        dataIndex: 'requiredCompletionDate',
        key: 'requiredCompletionDate',
        render: (text, record) => {
          return text ? <div>{moment(text).format('YYYY-MM-DD')}</div> : <div></div>;
        }
      },
      {
        title: '实际完成时间',
        dataIndex: 'completionDate',
        key: 'completionDate',
        render: (text, record) => {
          return text ? <div>{moment(text).format('YYYY-MM-DD')}</div> : <div></div>;
        }
      },
      {
        title: '完成情况',
        dataIndex: 'completionDesc',
        key: 'completionDesc', ellipsis: true
      },

      {
        title: '是否逾期', dataIndex: 'isOverdue', key: 'isOverdue',
        render: (value, record) => {
          const {completionDate, requiredCompletionDate} = record;
          const day1 = moment(requiredCompletionDate).format('YYYY-MM-DD');
          const day2 = moment().format('YYYY-MM-DD');

          const _str = moment(day2).valueOf() > moment(day1).valueOf() ? <Tag color={'#f00'}>已逾期</Tag> :
            <Tag color={'#00f'}>未逾期</Tag>;
          // let str = completionDate ? <Tag color={'#0f0'}>已完成</Tag> : _str;
          return <div>{_str}</div>;
        }
      }, {
        title: '是否完成', dataIndex: 'isEnded', key: 'isEnded',
        render: (value, record) => {
          return value ? <Tag color={'#0f0'}>是</Tag> : <Tag color={'#555'}>否</Tag>;
        }
      },
      {
        title: '操作', dataIndex: 'operation', key: 'operation',
        width: 220, fixed: 'right',
        render: (value, record) => {
          const {code, isEnded} = record;
          return (
            <span>
                   {<a style={{marginRight: '6px'}}
                       onClick={() => {
                         ModalView.open(ModalTaskDetail, {
                           title: "详情",
                           width: '1080px'
                         }, {
                           workRecord: record, model
                         });
                       }}
                   >详情</a>}
              {!isChild && <a style={{marginRight: '6px'}}
                              disabled={!isEnded}
                              onClick={() => {
                                this.props.dispatch({
                                  type: 'work/endWork',
                                  payload: {code, isEnded: false}
                                }).then(res => {
                                  this.requestReturn(res);
                                  this.componentDidMount();
                                });
                              }}
              >驳回</a>}
            </span>
          );
        }
      }
    );

    return temp;
  };
  picHandleCancel = () => this.setState({previewVisible: false});
  picHandlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj);
      console.log(file.preview);
    }
    const temp = this.state;

    temp['previewImage'] = file.url || file.preview;
    temp['previewVisible'] = true;
    this.setState({...temp});
  };
  picHandleChange = ({fileList}) => {
    _.map(fileList, async file => {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj);
        //file.thumbUrl = file.response ? file.response.data : fileList.file.thumbUrl;
      }
    });
    const temp = this.state;
    temp.fileList = fileList;
    this.setState({...temp});
  };
  getCard = (files) => {
    const temp = [];
    _.map(files, file => {
      temp.push(<Card
        hoverable
        style={{width: 640}}
        cover={<img alt="example" src={file.preview}/>}
      >
      </Card>);
    });
    return temp;
  };

  render() {
    const {style, cols = 2, work = {}, works = [], form} = this.props;
    const {
      code,
      completionDesc,
      memo,
      isAdmin,
      isEnded,
      relationWorkCode,
      isRelation,
      relationDesc,
      workList = []
    } = work;

    const model = this.props[`${table}Model`];
    if (!model) return <div></div>;
    const loginInfo = this.getLoginInfo();
    const {nickname} = loginInfo;
    const childWorks = [];
    _.map(works, async work => {
      const {createUsername} = work;
      if (nickname !== createUsername) {
        childWorks.push(work);
      }
    });
    const labels = [];
    if (relationWorkCode) {
      labels.push({label: '关联任务编码', key: "relationWorkCode", _type: 'string'});
    }
    labels.push(...[{label: '任务编码', key: "code", _type: 'string'},
      {label: '事项', key: "desc", _type: 'string'},
      // {label: '责任人', key: "username",_type:'string'},
      {label: '要求完成时间', key: "requiredCompletionDate", _type: 'date'},
      {label: '实际完成时间', key: "completionDate", _type: 'date'},
      {label: '完成情况', key: "completionDesc", _type: 'string'},
      {label: '备注', key: "memo", _type: 'string'}
    ]);
    const endWorkButtonStr = isEnded ? "未完成任务" : "完成任务";
    const endWorkButtonType = isEnded ? "dashed" : "primary";
    let {
      previewVisible,
      previewImage,
      fileList = work.fileList
    } = this.state;
    const uploadPicButton = (
      <div>
        <Icon type="plus"/>
        <div className="ant-upload-text">上传图片</div>
      </div>
    );
    return (
      <div style={{...style}}>
        <Tabs defaultActiveKey={1}>
          <TabPane tab={'工作'} key="1">
            <ViewTitle
              title={'工作任务信息'}
              level={1}
              actions={isAdmin && <Button disabled={isEnded && !isAdmin} type={endWorkButtonType} onClick={() => {
                form.validateFields((err, values) => {
                  if (err) {
                    const {code} = err;
                    const {errors} = code;
                    errors.forEach(item => {
                      notification.error(item);
                    });
                    return;
                  }
                  values.code = code;
                  values.fileList = this.state.fileList;
                  values.completionDate = isEnded ? "" : moment()
                    .format('YYYY-MM-DD');
                  values.isEnded = !isEnded;
                  this.props.dispatch({
                    type: 'work/endWork',
                    payload: values
                  }).then(res => {
                    if (isRelation && !isEnded) {
                      notify({type: 'info', message: "有关联任务", duration: 4});
                      ModalView.open(ModalCreateOrEditWork,
                        {
                          title: '创建关联任务',
                          width: '1080px'
                        }, {
                          table,
                          isTimer: false, relationWorkCode: code,
                          record: {
                            desc: relationDesc,
                            relationWorkCode: code,
                            code: 'WRK' + moment().format('YYYYMMDDHHmmss')
                          },
                          callback: (payload) => {
                            payload.isAdmin = this.getLoginInfo().isAdmin;
                            this.props.dispatch({
                              type: 'work/createWork',
                              payload
                            }).then(res => {
                              this.requestReturn(res);
                              this.componentDidMount();
                            });
                          }
                        });
                    }

                    this.requestReturn(res);
                    this.componentDidMount();
                  });
                });
              }}
              >{endWorkButtonStr}</Button>}
            ></ViewTitle>
            <DescGroup
              {...{
                labels: labels,
                values: work,
                size: 'small',
                column: cols
              }}
            ></DescGroup>
            <ViewTitle
              title={'分配工作任务列表'}
              level={1}
            ></ViewTitle>
            <Table
              className={styles.antTable}
              bordered={true}
              columns={this.columns()}
              dataSource={workList}
              scroll={{x: true}}
              pagination={{
                current: this.state.current,
                total: this.state.total,
                showSizeChanger: true,
                onChange: page => {
                  this.state.current = page;
                  this.componentDidMount();
                },
                onShowSizeChange: (current, pageSize) => {
                  this.state.current = 1;
                  this.state.pageSize = pageSize;
                  this.componentDidMount();
                }
              }}
            ></Table>
            {this.getCard(fileList)}
          </TabPane>
          {!isAdmin && <TabPane tab={'处理'} key="2">
            <ViewTitle
              title={'处理任务信息'}
              level={1}
              actions={<Button disabled={isEnded && !isAdmin} type={endWorkButtonType} onClick={() => {
                form.validateFields((err, values) => {
                  if (err) {
                    const {code} = err;
                    const {errors} = code;
                    errors.forEach(item => {
                      notification.error(item);
                    });
                    return;
                  }
                  values.code = code;
                  values.fileList = this.state.fileList;
                  values.completionDate = isEnded ? "" : moment()
                    .format('YYYY-MM-DD');
                  values.isEnded = !isEnded;
                  this.props.dispatch({
                    type: 'work/endWork',
                    payload: values
                  }).then(res => {
                    this.requestReturn(res);
                    this.componentDidMount();
                  });
                });
              }}
              >{endWorkButtonStr}</Button>}
            >
            </ViewTitle>
            <FormLayout form={form} cols={1}>
              <FormField
                label={'完成情况'}
                name={'completionDesc'}
                initialValue={completionDesc}
                required={true}
              >
                <TextArea style={{width: '90%'}}
                ></TextArea>
              </FormField>
            </FormLayout>

            {<div style={{marginLeft: '64px'}}>
              <Upload
                action={'http://127.0.0.1:18008/api/global/upload?type=inboundLot'} // 没有用，直接存图片流文件
                listType="picture-card"
                fileList={fileList}
                accept={".png,.jpg"}
                onPreview={this.picHandlePreview}
                onChange={this.picHandleChange}
                onDownload={file => {
                  console.log('ondownlad', file);
                }}
                beforeUpload={(file, fileList) => {
                  const isLt2M = file.size / 1024 / 1024 < 2;
                  if (!isLt2M) {
                    notify({type: 'error', message: '文件过大！'});
                    return isLt2M;
                  }
                  return false;
                }}
              >
                {uploadPicButton}
              </Upload>
              <Modal visible={previewVisible} footer={null} onCancel={this.picHandleCancel}>
                <img alt="example" style={{width: '100%'}} src={previewImage}/>
              </Modal>
            </div>}
          </TabPane>}
          {isAdmin && <TabPane tab={'子任务'} key="3">
            <ViewTitle
              title={'子任务列表'}
              level={1}

            ></ViewTitle>
            <Table
              className={styles.antTable}
              bordered={true}
              columns={this.columns(true)}
              dataSource={childWorks}
              scroll={{x: true}}
              pagination={{
                current: this.state.current,
                total: this.state.total,
                showSizeChanger: true,
                onChange: page => {
                  this.state.current = page;
                  this.componentDidMount();
                },
                onShowSizeChange: (current, pageSize) => {
                  this.state.current = 1;
                  this.state.pageSize = pageSize;
                  this.componentDidMount();
                }
              }}
            ></Table>
          </TabPane>}
        </Tabs>

      </div>

    );
  }
}

